﻿using NHibernate;
using ProgressTracker.Data.Abstract;
using ProgressTracker.Data.Entities;
using System;

namespace ProgressTracker.Data.Concrete
{
    public class DayRepository : IDayRepository 
    {
        ISession _session;
        ITaskRepository _taskRepo;
        IUserRepository _userRepo;

        public DayRepository(ISession session,
            ITaskRepository taskRepo,
            IUserRepository userRepo)
        {
            _session = session;
            _taskRepo = taskRepo;
            _userRepo = userRepo;
        }

        public Day GetDay(DateTime date, string userEmail)
        {
            var dayQuery = _session.QueryOver<Day>()
                .Where(x => x.Date == date)
                .JoinQueryOver<User>(x => x.User)
                    .Where(u => u.Email == userEmail)
                .List();

            if(dayQuery.Count < 1)
            {
                return null;
            }
            
            return dayQuery[0];
        }

        public void AddTaskToDay(Day day, Task task)
        {
            var dayTask = new DayTask
            {
                Day = day,
                Task = task,
                TaskComplete = false
            };

            day.DayTasks.Add(dayTask);
            task.DayTasks.Add(dayTask);

            Save(day);
        }

        public void Save(Day day)
        {
            using(var transaction = _session.BeginTransaction())
            {
                _session.SaveOrUpdate(day);
                transaction.Commit();
            }
        }

        private int GetUserId(string userEmail)
        {
            var user = _userRepo.GetUserByEmail(userEmail);

            return user.Id;
        }

        public Day CreateNewDay(DateTime date, string userEmail)
        {
            var user = _userRepo.GetUserByEmail(userEmail);

            var day = new Day
            {
                Date = date,
                User = user
            };

            var currentTasks = _taskRepo.GetCurrentTasks(user.Id);

            foreach(var task in currentTasks)
            {
                var dayTask = new DayTask
                {
                    Day = day,
                    Task = task,
                    TaskComplete = false
                };

                day.DayTasks.Add(dayTask);
                task.DayTasks.Add(dayTask);
            }

            Save(day);

            return day;
        }
    }
}
